home *** CD-ROM | disk | FTP | other *** search
/ PD Collection CD 1 / PD Collection CD 1.iso / textual / gnudiff / C / Diff3 < prev    next >
Text File  |  1991-10-02  |  48KB  |  1,648 lines

  1. /* Three-way file comparison program (diff3) for Project GNU
  2.    Copyright (C) 1988, 1989 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18.  
  19. /* Written by Randy Smith */
  20.  
  21. /* 
  22.  * Include files.
  23.  */
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <stdio.h>
  27. #include <ctype.h>
  28. #include "kernel.h"
  29. #include "getopt.h"
  30.  
  31. /* Utility routines - pipes */
  32. extern FILE *popen (const char *, const char *);
  33. extern void pclose (FILE *);
  34.  
  35. /* The name of the diff program to use */
  36. #ifndef DIFF_PROGRAM
  37. #define DIFF_PROGRAM "Diff"
  38. #endif
  39.  
  40. /* Define needed BSD functions in terms of ANSI library.  */
  41. #define bcmp(s1,s2,n)    memcmp((s1),(s2),(n))
  42. #define bzero(s,n)    memset((s),0,(n))
  43.  
  44. /*
  45.  * Internal data structures and macros for the diff3 program; includes
  46.  * data structures for both diff3 diffs and normal diffs.
  47.  */
  48.  
  49. /*
  50.  * Different files within a diff
  51.  */
  52. #define    FILE0    0
  53. #define    FILE1    1
  54. #define    FILE2    2
  55.  
  56. /*
  57.  * Three way diffs are build out of two two-way diffs; the file which
  58.  * the two two-way diffs share is:
  59.  */
  60. #define    FILEC    FILE0
  61.  
  62. /* The ranges are indexed by */
  63. #define    START    0
  64. #define    END    1
  65.  
  66. enum diff_type {
  67.   ERROR,            /* Should not be used */
  68.   ADD,                /* Two way diff add */
  69.   CHANGE,            /* Two way diff change */
  70.   DELETE,            /* Two way diff delete */
  71.   DIFF_ALL,            /* All three are different */
  72.   DIFF_1ST,            /* Only the first is different */
  73.   DIFF_2ND,            /* Only the second */
  74.   DIFF_3RD            /* Only the third */
  75. };
  76.  
  77. /* Two-way diff */
  78. struct diff_block {
  79.   int ranges[2][2];            /* Ranges are inclusive */
  80.   char **lines[2];        /* The actual lines (may contain nulls) */
  81.   int *lengths[2];        /* Line lengths (including newlines, if any) */
  82.   struct diff_block *next;
  83. };
  84.  
  85. /* Three-way diff */
  86.  
  87. struct diff3_block {
  88.   enum diff_type correspond;    /* Type of diff */
  89.   int ranges[3][2];            /* Ranges are inclusive */
  90.   char **lines[3];        /* The actual lines (may contain nulls) */
  91.   int *lengths[3];        /* Line lengths (including newlines, if any) */
  92.   struct diff3_block *next;
  93. };
  94.  
  95. /*
  96.  * Access the ranges on a diff block.
  97.  */
  98. #define    D_LOWLINE(diff, filenum)    \
  99.   ((diff)->ranges[filenum][START])
  100. #define    D_HIGHLINE(diff, filenum)    \
  101.   ((diff)->ranges[filenum][END])
  102. #define    D_NUMLINES(diff, filenum)    \
  103.   (D_HIGHLINE((diff), (filenum)) - D_LOWLINE((diff), (filenum)) + 1)
  104.  
  105. /*
  106.  * Access the line numbers in a file in a diff by relative line
  107.  * numbers (i.e. line number within the diff itself).  Note that these
  108.  * are lvalues and can be used for assignment.
  109.  */
  110. #define    D_RELNUM(diff, filenum, linenum)    \
  111.   (*((diff)->lines[filenum] + linenum))
  112. #define    D_RELLEN(diff, filenum, linenum)    \
  113.   (*((diff)->lengths[filenum] + linenum))
  114.  
  115. /*
  116.  * And get at them directly, when that should be necessary.
  117.  */
  118. #define    D_LINEARRAY(diff, filenum)    \
  119.   ((diff)->lines[filenum])
  120. #define    D_LENARRAY(diff, filenum)    \
  121.   ((diff)->lengths[filenum])
  122.  
  123. /*
  124.  * Next block.
  125.  */
  126. #define    D_NEXT(diff)    ((diff)->next)
  127.  
  128. /*
  129.  * Access the type of a diff3 block.
  130.  */
  131. #define    D3_TYPE(diff)    ((diff)->correspond)
  132.  
  133. /*
  134.  * Line mappings based on diffs.  The first maps off the top of the
  135.  * diff, the second off of the bottom.
  136.  */
  137. #define    D_HIGH_MAPLINE(diff, fromfile, tofile, lineno)    \
  138.   ((lineno)                        \
  139.    - D_HIGHLINE ((diff), (fromfile))            \
  140.    + D_HIGHLINE ((diff), (tofile)))
  141.  
  142. #define    D_LOW_MAPLINE(diff, fromfile, tofile, lineno)    \
  143.   ((lineno)                        \
  144.    - D_LOWLINE ((diff), (fromfile))            \
  145.    + D_LOWLINE ((diff), (tofile)))
  146.  
  147. /*
  148.  * General memory allocation function.
  149.  */
  150. #define    ALLOCATE(number, type)    \
  151.   (type *) xmalloc ((number) * sizeof (type))
  152.  
  153. /* Function declarations */
  154. extern char *read_diff (char *, char *, char **);
  155. extern char *scan_diff_line (char *, char **, int *, char *, char);
  156.  
  157. extern enum diff_type process_diff_control (char **, struct diff_block *);
  158.  
  159. extern int compare_line_list (char **, int *, char **, int *, int);
  160. extern int copy_stringlist (char **, int *, char **, int *, int);
  161. extern int myread (FILE *, char *, int);
  162. extern int output_diff3_edscript (FILE *, struct diff3_block *, int *, int *, char *, char *, char *);
  163. extern int output_diff3_merge (FILE *, FILE *, struct diff3_block *, int *, int *, char *, char *, char *);
  164.  
  165. extern struct diff3_block *reverse_diff3_blocklist (struct diff3_block *);
  166. extern struct diff3_block *using_to_diff3_block (struct diff_block **, struct diff_block **, int, int, struct diff3_block *);
  167. extern struct diff3_block *create_diff3_block (int, int, int, int, int, int);
  168. extern struct diff3_block *make_3way_diff (struct diff_block *, struct diff_block *);
  169.  
  170. extern struct diff_block *process_diff (char *, char *);
  171.  
  172. extern void *xmalloc (int);
  173. extern void *xrealloc (void *, int);
  174.  
  175. extern void fatal (char *);
  176. extern void output_diff3 (FILE *, struct diff3_block *, int *, int *);
  177.  
  178. /*
  179.  * Options variables for flags set on command line.
  180.  *
  181.  * ALWAYS_TEXT: Treat all files as text files; never treat as binary.
  182.  *
  183.  * EDSCRIPT: Write out an ed script instead of the standard diff3 format.
  184.  *
  185.  * FLAGGING: Indicates that in the case of overlapping diffs (type
  186.  * DIFF_ALL), the lines which would normally be deleted from file 1
  187.  * should be preserved with a special flagging mechanism.
  188.  *
  189.  * DONT_WRITE_OVERLAP: 1 if information for overlapping diffs should
  190.  * not be output.
  191.  *
  192.  * DONT_WRITE_SIMPLE: 1 if information for non-overlapping diffs
  193.  * should not be output. 
  194.  *
  195.  * FINALWRITE: 1 if a :wq should be included at the end of the script
  196.  * to write out the file being edited.
  197.  *
  198.  * MERGE: output a merged file.
  199.  */
  200. int always_text;
  201. int edscript;
  202. int flagging;
  203. int dont_write_overlap;
  204. int dont_write_simple;
  205. int finalwrite;
  206. int merge;
  207.  
  208. /* Argument processing */
  209.  
  210. #define OPTIONS "?3aefL:imx"
  211.  
  212. static struct option longopts[] =
  213. {
  214.   {"ed-no-overlap", 0, 0, '3'},
  215.   {"all-text", 0, 0, 'a'},
  216.   {"ascii", 0, 0, 'a'},
  217.   {"text", 0, 0, 'a'},
  218.   {"ed-script", 0, 0, 'e'},
  219.   {"flag", 0, 0, 'f'},
  220.   {"file-label", 1, 0, 'L'},
  221.   {"write-cmd", 0, 0, 'i'},
  222.   {"merge", 0, 0, 'm'},
  223.   {"ed-all-changed", 0, 0, 'x'},
  224. };
  225.  
  226. #define USAGE \
  227. "Usage: Diff3 [options] file1 file2 file3\n" \
  228. "\n" \
  229. "Options:\n" \
  230. "Short   Long                            Description\n" \
  231. "-3      +ed-no-overlap                  Ed script (no overlaps included)\n" \
  232. "-a      +text +all-text +ascii          Treat all files as text\n" \
  233. "-e      +ed-script                      Ed script\n" \
  234. "-f      +flag                           Flag overlapping changes\n" \
  235. "-i      +write-cmd                      Include a write command in the script\n" \
  236. "-L      +file-label=label               Label file1, file3 with <label>\n" \
  237. "-m      +merge                          Merge directly onto standard output\n" \
  238. "-x      +ed-all-changed                 Ed script (overlaps only)\n" \
  239. "\n" \
  240. "The ed script options write a script which would convert file1, by\n" \
  241. "incorporating the changes which make file3 from file2. The flag\n" \
  242. "variations write out both file1 and file3 versions where all 3 files\n" \
  243. "differ.\n"
  244.  
  245. char *argv0;
  246. char diff_program[] = DIFF_PROGRAM;
  247.  
  248. /*
  249.  * Main program.  Calls diff twice on two pairs of input files,
  250.  * combines the two diffs, and outputs them.
  251.  */
  252. int main (int argc, char *argv[])
  253. {
  254.   int c, i;
  255.   int mapping[3];
  256.   int rev_mapping[3];
  257.   int incompat;
  258.   int overlaps_found;
  259.   struct diff_block *thread1, *thread2;
  260.   struct diff3_block *diff;
  261.   int tag_count = 0;
  262.   /* Element 0 is for file 0, element 1 is for file 2.  */
  263.   char *tag_strings[2];
  264.   char *commonname;
  265.   int longind;
  266.  
  267.   incompat = 0;
  268.   tag_strings[0] = tag_strings[1] = 0;
  269.  
  270.   argv0 = argv[0];
  271.   
  272.   while ((c = getopt_long (argc, argv, OPTIONS, longopts, &longind)) != OPT_END)
  273.     {
  274.       if (c == OPT_LONG)        /* Long option */
  275.     c = longopts[longind].val;
  276.       switch (c)
  277.     {
  278.     case '3':
  279.       dont_write_overlap = 1;
  280.       incompat++;
  281.       break;
  282.     case 'a':
  283.       always_text = 1;
  284.       break;
  285.     case 'e':
  286.       incompat++;
  287.       break;
  288.     case 'f':
  289.       flagging = 1;
  290.       break;
  291.     case 'i':
  292.       finalwrite = 1;
  293.       break;
  294.     case 'L':
  295.       /* We can only handle one or two -L arguments.  */
  296.       if (tag_count >= 2)
  297.         {
  298.           fprintf (stderr, "Diff3: Only 2 file labels allowed\n");
  299.           exit (2);
  300.         }
  301.       tag_strings[tag_count++] = optarg;
  302.       break;
  303.     case 'm':
  304.       merge = 1;
  305.       break;
  306.     case 'x':
  307.       dont_write_simple = 1;
  308.       incompat++;
  309.       break;
  310.     case '?':
  311.       fprintf (stderr, "%s", USAGE);
  312.       exit (0);
  313.     case OPT_ERR:
  314.     default:
  315.       exit (2);
  316.     }
  317.     }
  318.  
  319.   edscript = incompat & ~merge;  /* -ex3 without -m implies ed script.  */
  320.   flagging |= ~incompat & merge;  /* -m without -ex3 implies -f.  */
  321.  
  322.   /* Ensure at most one of -ex3.  */
  323.   if (incompat > 1)
  324.     {
  325.       fprintf (stderr, "Diff3: Only one of -e -x and -3 allowed\n");
  326.       exit (2);
  327.     }
  328.  
  329.   /* -i needs one of -ex3; -i -m would rewrite input file.  */
  330.   if (finalwrite & (~incompat | merge))
  331.     {
  332.       fprintf (stderr, "Diff3: Must specify -e, -x or -3 with -i\n");
  333.       exit (2);
  334.     }
  335.  
  336.   /* -L requires -f.  */
  337.   if (tag_count && ! flagging)
  338.     {
  339.       fprintf (stderr, "Diff3: Must specify -f with -L\n");
  340.       exit (2);
  341.     }
  342.  
  343.   if (argc - optind != 3)
  344.     {
  345.       fprintf (stderr, "Diff3: Requires 3 arguments\n");
  346.       exit (2);
  347.     }
  348.  
  349.   if (tag_strings[0] == 0)
  350.     tag_strings[0] = argv[optind];
  351.   if (tag_strings[1] == 0)
  352.     tag_strings[1] = argv[optind + 2];
  353.  
  354.   if (*argv[optind] == '-' && *(argv[optind] + 1) == '\0')
  355.     {
  356.       /* Sigh.  We've got standard input as the first arg. We can't */
  357.       /* call diff twice on stdin */
  358.       if (! strcmp (argv[optind + 1], "-") || ! strcmp (argv[optind + 2], "-"))
  359.     fatal ("'-' specified for more than one input file");
  360.       mapping[0] = 1;
  361.       mapping[1] = 2;
  362.       mapping[2] = 0;
  363.       rev_mapping[1] = 0;
  364.       rev_mapping[2] = 1;
  365.       rev_mapping[0] = 2;
  366.     }
  367.   else
  368.     {
  369.       /* Normal, what you'd expect */
  370.       mapping[0] = 0;
  371.       mapping[1] = 1;
  372.       mapping[2] = 2;
  373.       rev_mapping[0] = 0;
  374.       rev_mapping[1] = 1;
  375.       rev_mapping[2] = 2;
  376.     }
  377.  
  378.   for (i = 0; i < 3; i++)
  379.     if (argv[optind + i][0] != '-' || argv[optind + i][1] != '\0')
  380.       {
  381.     int res;
  382.     _kernel_osfile_block blk;
  383.  
  384.     res = _kernel_osfile (5, argv[optind + i], &blk);
  385.  
  386.     if (res == _kernel_ERROR)
  387.       {
  388.         _kernel_oserror *err = _kernel_last_oserror();
  389.         fprintf(stderr, "%s: Cannot read %s (Error %d - %s)\n",
  390.             argv0, argv[optind+i], err->errnum, err->errmess);
  391.         exit (2);
  392.       }
  393.     else if (res != 1)
  394.       {
  395.         fprintf(stderr, "%s: %s %s\n", argv0, argv[optind+i],
  396.             res == 2 ? "is a directory" : "does not exist");
  397.         exit (2);
  398.       }
  399.       }
  400.  
  401.   commonname = argv[optind + rev_mapping[0]];
  402.   thread1 = process_diff (commonname, argv[optind + rev_mapping[1]]);
  403.   thread2 = process_diff (commonname, argv[optind + rev_mapping[2]]);
  404.   diff = make_3way_diff (thread1, thread2);
  405.   if (edscript)
  406.     overlaps_found
  407.       = output_diff3_edscript (stdout, diff, mapping, rev_mapping,
  408.                    tag_strings[0], argv[optind+1], tag_strings[1]);
  409.   else if (merge)
  410.     {
  411.       if (! freopen (commonname, "r", stdin))
  412.     {
  413.       _kernel_oserror *err = _kernel_last_oserror();
  414.       if (err && err->errnum)
  415.         fprintf(stderr, "%s: Cannot read %s (Error %d - %s)\n",
  416.             argv0, commonname, err->errnum, err->errmess);
  417.       else
  418.         fprintf(stderr, "%s: Cannot read %s\n", argv0, commonname);
  419.       exit (2);
  420.     }
  421.       overlaps_found
  422.     = output_diff3_merge (stdin, stdout, diff, mapping, rev_mapping,
  423.                   tag_strings[0], argv[optind+1], tag_strings[1]);
  424.       if (ferror (stdin))
  425.     fatal ("Read error");
  426.     }
  427.   else
  428.     {
  429.       output_diff3 (stdout, diff, mapping, rev_mapping);
  430.       overlaps_found = 0;
  431.     }
  432.  
  433.   if (ferror (stdout) || fflush (stdout) != 0)
  434.     fatal ("Write error");
  435.   exit (overlaps_found);
  436. }
  437.       
  438. /*
  439.  * Routines that combine the two diffs together into one.  The
  440.  * algorithm used follows:
  441.  *
  442.  *   File0 is shared in common between the two diffs.
  443.  *   Diff01 is the diff between 0 and 1.
  444.  *   Diff02 is the diff between 0 and 2.
  445.  *
  446.  *     1) Find the range for the first block in File0.
  447.  *          a) Take the lowest of the two ranges (in File0) in the two
  448.  *             current blocks (one from each diff) as being the low
  449.  *             water mark.  Assign the upper end of this block as
  450.  *             being the high water mark and move the current block up
  451.  *             one.  Mark the block just moved over as to be used.
  452.  *        b) Check the next block in the diff that the high water
  453.  *             mark is *not* from.  
  454.  *           
  455.  *           *If* the high water mark is above
  456.  *             the low end of the range in that block, 
  457.  * 
  458.  *               mark that block as to be used and move the current
  459.  *                 block up.  Set the high water mark to the max of
  460.  *                 the high end of this block and the current.  Repeat b.
  461.  * 
  462.  *       2) Find the corresponding ranges in Files1 (from the blocks
  463.  *          in diff01; line per line outside of diffs) and in File2.
  464.  *          Create a diff3_block, reserving space as indicated by the ranges.
  465.  *        
  466.  *     3) Copy all of the pointers for file0 in.  At least for now,
  467.  *          do bcmp's between corresponding strings in the two diffs.
  468.  *        
  469.  *     4) Copy all of the pointers for file1 and 2 in.  Get what you
  470.  *          need from file0 (when there isn't a diff block, it's
  471.  *          identical to file0 within the range between diff blocks).
  472.  *        
  473.  *     5) If the diff blocks you used came from only one of the two
  474.  *         strings of diffs, then that file (i.e. the one other than
  475.  *         file 0 in that diff) is the odd person out.  If you used
  476.  *         diff blocks from both sets, check to see if files 1 and 2 match:
  477.  *        
  478.  *            Same number of lines?  If so, do a set of bcmp's (if a
  479.  *          bcmp matches; copy the pointer over; it'll be easier later
  480.  *          if you have to do any compares).  If they match, 1 & 2 are
  481.  *          the same.  If not, all three different.
  482.  * 
  483.  *   Then you do it again, until you run out of blocks. 
  484.  * 
  485.  */
  486.  
  487. /* 
  488.  * This routine makes a three way diff (chain of diff3_block's) from two
  489.  * two way diffs (chains of diff_block's).  It is assumed that each of
  490.  * the two diffs passed are off of the same file (i.e. that each of the
  491.  * diffs were made "from" the same file).  The three way diff pointer
  492.  * returned will have numbering 0--the common file, 1--the other file
  493.  * in diff1, and 2--the other file in diff2.
  494.  */
  495. struct diff3_block *make_3way_diff (struct diff_block *thread1,
  496.                     struct diff_block *thread2)
  497. {
  498. /*
  499.  * This routine works on the two diffs passed to it as threads.
  500.  * Thread number 0 is diff1, thread number 1 is diff2.  The USING
  501.  * array is set to the base of the list of blocks to be used to
  502.  * construct each block of the three way diff; if no blocks from a
  503.  * particular thread are to be used, that element of the using array
  504.  * is set to 0.  The elements LAST_USING array are set to the last
  505.  * elements on each of the using lists.
  506.  *
  507.  * The HIGH_WATER_MARK is set to the highest line number in File 0
  508.  * described in any of the diffs in either of the USING lists.  The
  509.  * HIGH_WATER_THREAD names the thread.  Similarly the BASE_WATER_MARK
  510.  * and BASE_WATER_THREAD describe the lowest line number in File 0
  511.  * described in any of the diffs in either of the USING lists.  The
  512.  * HIGH_WATER_DIFF is the diff from which the HIGH_WATER_MARK was
  513.  * taken. 
  514.  *
  515.  * The HIGH_WATER_DIFF should always be equal to LAST_USING
  516.  * [HIGH_WATER_THREAD].  The OTHER_DIFF is the next diff to check for
  517.  * higher water, and should always be equal to
  518.  * CURRENT[HIGH_WATER_THREAD ^ 0x1].  The OTHER_THREAD is the thread
  519.  * in which the OTHER_DIFF is, and hence should always be equal to
  520.  * HIGH_WATER_THREAD ^ 0x1.
  521.  *
  522.  * The variable LAST_DIFF is kept set to the last diff block produced
  523.  * by this routine, for line correspondence purposes between that diff
  524.  * and the one currently being worked on.  It is initialized to
  525.  * ZERO_DIFF before any blocks have been created.
  526.  */
  527.  
  528.   struct diff_block
  529.     *using[2],
  530.     *last_using[2],
  531.     *current[2];
  532.  
  533.   int
  534.     high_water_mark;
  535.  
  536.   int
  537.     high_water_thread,
  538.     base_water_thread,
  539.     other_thread;
  540.  
  541.   struct diff_block
  542.     *high_water_diff,
  543.     *other_diff;
  544.  
  545.   struct diff3_block
  546.     *result,
  547.     *tmpblock,
  548.     *result_last,
  549.     *last_diff;
  550.  
  551.   static struct diff3_block zero_diff = {
  552.       ERROR,
  553.       { {0, 0}, {0, 0}, {0, 0} },
  554.       { (char **) 0, (char **) 0, (char **) 0 },
  555.       { (int *) 0, (int *) 0, (int *) 0 },
  556.       (struct diff3_block *) 0
  557.       };
  558.  
  559.   /* Initialization */
  560.   result = result_last = (struct diff3_block *) 0;
  561.   current[0] = thread1; current[1] = thread2;
  562.   last_diff = &zero_diff;
  563.  
  564.   /* Sniff up the threads until we reach the end */
  565.  
  566.   while (current[0] || current[1])
  567.     {
  568.       using[0] = using[1] = last_using[0] = last_using[1] =
  569.     (struct diff_block *) 0;
  570.  
  571.       /* Setup low and high water threads, diffs, and marks.  */
  572.       if (!current[0])
  573.     base_water_thread = 1;
  574.       else if (!current[1])
  575.     base_water_thread = 0;
  576.       else
  577.     base_water_thread =
  578.       (D_LOWLINE (current[0], FILE0) > D_LOWLINE (current[1], FILE0));
  579.  
  580.       high_water_thread = base_water_thread;
  581.       
  582.       high_water_diff = current[high_water_thread];
  583.     
  584. #if 0
  585.       /* low and high waters start off same diff */
  586.       base_water_mark = D_LOWLINE (high_water_diff, FILE0);
  587. #endif
  588.  
  589.       high_water_mark = D_HIGHLINE (high_water_diff, FILE0);
  590.  
  591.       /* Make the diff you just got info from into the using class */
  592.       using[high_water_thread]
  593.     = last_using[high_water_thread]
  594.     = high_water_diff;
  595.       current[high_water_thread] = high_water_diff->next;
  596.       last_using[high_water_thread]->next
  597.     = (struct diff_block *) 0;
  598.  
  599.       /* And mark the other diff */
  600.       other_thread = high_water_thread ^ 0x1;
  601.       other_diff = current[other_thread];
  602.  
  603.       /* Shuffle up the ladder, checking the other diff to see if it
  604.          needs to be incorporated */
  605.       while (other_diff
  606.          && D_LOWLINE (other_diff, FILE0) <= high_water_mark + 1)
  607.     {
  608.  
  609.       /* Incorporate this diff into the using list.  Note that
  610.          this doesn't take it off the current list */
  611.       if (using[other_thread])
  612.         last_using[other_thread]->next = other_diff;
  613.       else
  614.         using[other_thread] = other_diff;
  615.       last_using[other_thread] = other_diff;
  616.  
  617.       /* Take it off the current list.  Note that this following
  618.          code assumes that other_diff enters it equal to
  619.          current[high_water_thread ^ 0x1] */
  620.       current[other_thread]
  621.         = current[other_thread]->next;
  622.       other_diff->next
  623.         = (struct diff_block *) 0;
  624.  
  625.       /* Set the high_water stuff
  626.          If this comparison is equal, then this is the last pass
  627.          through this loop; since diff blocks within a given
  628.          thread cannot overlap, the high_water_mark will be
  629.          *below* the range_start of either of the next diffs. */
  630.  
  631.       if (high_water_mark < D_HIGHLINE (other_diff, FILE0))
  632.         {
  633.           high_water_thread ^= 1;
  634.           high_water_diff = other_diff;
  635.           high_water_mark = D_HIGHLINE (other_diff, FILE0);
  636.         }
  637.  
  638.       /* Set the other diff */
  639.       other_thread = high_water_thread ^ 0x1;
  640.       other_diff = current[other_thread];
  641.     }
  642.  
  643.       /* The using lists contain a list of all of the blocks to be
  644.          included in this diff3_block.  Create it.  */
  645.  
  646.       tmpblock = using_to_diff3_block (using, last_using,
  647.                        base_water_thread, high_water_thread,
  648.                        last_diff);
  649.  
  650.       if (!tmpblock)
  651.     fatal ("Internal: Screwup in format of diff blocks");
  652.  
  653.       /* Put it on the list */
  654.       if (result)
  655.     result_last->next = tmpblock;
  656.       else
  657.     result = tmpblock;
  658.       result_last = tmpblock;
  659.  
  660.       /* Setup corresponding lines correctly */
  661.       last_diff = tmpblock;
  662.     }
  663.   return result;
  664. }
  665.  
  666. /*
  667.  * using_to_diff3_block:
  668.  *   This routine takes two lists of blocks (from two separate diff
  669.  * threads) and puts them together into one diff3 block.
  670.  * It then returns a pointer to this diff3 block or 0 for failure.
  671.  *
  672.  * All arguments besides using are for the convenience of the routine;
  673.  * they could be derived from the using array.
  674.  * LAST_USING is a pair of pointers to the last blocks in the using
  675.  * structure.
  676.  * LOW_THREAD and HIGH_THREAD tell which threads contain the lowest
  677.  * and highest line numbers for File0.
  678.  * last_diff contains the last diff produced in the calling routine.
  679.  * This is used for lines mappings which would still be identical to
  680.  * the state that diff ended in.
  681.  *
  682.  * A distinction should be made in this routine between the two diffs
  683.  * that are part of a normal two diff block, and the three diffs that
  684.  * are part of a diff3_block.
  685.  */
  686. struct diff3_block *using_to_diff3_block (struct diff_block *using[],
  687.                       struct diff_block *last_using[],
  688.                       int low_thread, int high_thread,
  689.                       struct diff3_block *last_diff)
  690. {
  691.   int lowc, highc, low1, high1, low2, high2;
  692.   struct diff3_block *result;
  693.   struct diff_block *ptr;
  694.   int i;
  695.   int current0line;
  696.   
  697.   /* Find the range in file0 */
  698.   lowc = using[low_thread]->ranges[0][START];
  699.   highc = last_using[high_thread]->ranges[0][END];
  700.  
  701.   /* Find the ranges in the other files.
  702.      If using[x] is null, that means that the file to which that diff
  703.      refers is equivalent to file 0 over this range */
  704.   
  705.   if (using[0])
  706.     {
  707.       low1 = D_LOW_MAPLINE (using[0], FILE0, FILE1, lowc);
  708.       high1 = D_HIGH_MAPLINE (last_using[0], FILE0, FILE1, highc); 
  709.     }
  710.   else
  711.     {
  712.       low1 = D_HIGH_MAPLINE (last_diff, FILEC, FILE1, lowc);
  713.       high1 = D_HIGH_MAPLINE (last_diff, FILEC, FILE1, highc);
  714.     }
  715.  
  716.   /*
  717.    * Note that in the following, we use file 1 relative to the diff,
  718.    * and file 2 relative to the corresponding lines struct.
  719.    */
  720.   if (using[1])
  721.     {
  722.       low2 = D_LOW_MAPLINE (using[1], FILE0, FILE1, lowc);
  723.       high2 = D_HIGH_MAPLINE (last_using[1], FILE0, FILE1, highc); 
  724.     }
  725.   else
  726.     {
  727.       low2 = D_HIGH_MAPLINE (last_diff, FILEC, FILE2, lowc);
  728.       high2 = D_HIGH_MAPLINE (last_diff, FILEC, FILE2, highc);
  729.     }
  730.  
  731.   /* Create a block with the appropriate sizes */
  732.   result = create_diff3_block (lowc, highc, low1, high1, low2, high2);
  733.  
  734.   /* Copy over all of the information for File 0.  Return with a zero
  735.      if any of the compares failed. */
  736.   for (ptr = using[0]; ptr; ptr = D_NEXT (ptr))
  737.     {
  738.       int result_offset = D_LOWLINE (ptr, FILE0) - lowc;
  739.       int copy_size
  740.     = D_HIGHLINE (ptr, FILE0) - D_LOWLINE (ptr, FILE0) + 1;
  741.       
  742.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE0),
  743.                 D_LENARRAY (ptr, FILE0),
  744.                 D_LINEARRAY (result, FILEC) + result_offset,
  745.                 D_LENARRAY (result, FILEC) + result_offset,
  746.                 copy_size))
  747.     return 0;
  748.     }
  749.  
  750.   for (ptr = using[1]; ptr; ptr = D_NEXT (ptr))
  751.     {
  752.       int result_offset = D_LOWLINE (ptr, FILEC) - lowc;
  753.       int copy_size
  754.     = D_HIGHLINE (ptr, FILEC) - D_LOWLINE (ptr, FILEC) + 1;
  755.       
  756.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE0),
  757.                 D_LENARRAY (ptr, FILE0),
  758.                 D_LINEARRAY (result, FILEC) + result_offset,
  759.                 D_LENARRAY (result, FILEC) + result_offset,
  760.                 copy_size))
  761.     return 0;
  762.     }
  763.  
  764.   /* Copy stuff for file 1.  First deal with anything that might be
  765.      before the first diff. */
  766.  
  767.   for (i = 0;
  768.        i + low1 < (using[0] ? D_LOWLINE (using[0], FILE1) : high1 + 1);
  769.        i++)
  770.     {
  771.       D_RELNUM (result, FILE1, i) = D_RELNUM (result, FILEC, i);
  772.       D_RELLEN (result, FILE1, i) = D_RELLEN (result, FILEC, i);
  773.     }
  774.   
  775.   for (ptr = using[0]; ptr; ptr = D_NEXT (ptr))
  776.     {
  777.       int result_offset = D_LOWLINE (ptr, FILE1) - low1;
  778.       int copy_size
  779.     = D_HIGHLINE (ptr, FILE1) - D_LOWLINE (ptr, FILE1) + 1;
  780.  
  781.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE1),
  782.                 D_LENARRAY (ptr, FILE1),
  783.                 D_LINEARRAY (result, FILE1) + result_offset,
  784.                 D_LENARRAY (result, FILE1) + result_offset,
  785.                 copy_size))
  786.     return 0;
  787.  
  788.       /* Catch the lines between here and the next diff */
  789.       current0line = D_HIGHLINE (ptr, FILE0) + 1 - lowc;
  790.       for (i = D_HIGHLINE (ptr, FILE1) + 1 - low1;
  791.        i < (D_NEXT (ptr) ?
  792.         D_LOWLINE (D_NEXT (ptr), FILE1) :
  793.         high1 + 1) - low1;
  794.        i++)
  795.     {
  796.       D_RELNUM (result, FILE1, i)
  797.         = D_RELNUM (result, FILEC, current0line);
  798.       D_RELLEN (result, FILE1, i)
  799.         = D_RELLEN (result, FILEC, current0line++);
  800.     }
  801.     }
  802.  
  803.   /* Copy stuff for file 2.  First deal with anything that might be
  804.      before the first diff. */
  805.  
  806.   for (i = 0;
  807.        i + low2 < (using[1] ? D_LOWLINE (using[1], FILE1) : high2 + 1);
  808.        i++)
  809.     {
  810.       D_RELNUM (result, FILE2, i) = D_RELNUM (result, FILEC, i);
  811.       D_RELLEN (result, FILE2, i) = D_RELLEN (result, FILEC, i);
  812.     }
  813.   
  814.   for (ptr = using[1]; ptr; ptr = D_NEXT (ptr))
  815.     {
  816.       int result_offset = D_LOWLINE (ptr, FILE1) - low2;
  817.       int copy_size
  818.     = D_HIGHLINE (ptr, FILE1) - D_LOWLINE (ptr, FILE1) + 1;
  819.  
  820.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE1),
  821.                 D_LENARRAY (ptr, FILE1),
  822.                 D_LINEARRAY (result, FILE2) + result_offset,
  823.                 D_LENARRAY (result, FILE2) + result_offset,
  824.                 copy_size))
  825.     return 0;
  826.  
  827.       /* Catch the lines between here and the next diff */
  828.       current0line = D_HIGHLINE (ptr, FILE0) + 1 - lowc;
  829.       for (i = D_HIGHLINE (ptr, FILE1) + 1 - low2;
  830.        i < (D_NEXT (ptr) ?
  831.         D_LOWLINE (D_NEXT (ptr), FILE1) :
  832.         high2 + 1) - low2;
  833.        i++)
  834.     {
  835.       D_RELNUM (result, FILE2, i)
  836.         = D_RELNUM (result, FILEC, current0line);
  837.       D_RELLEN (result, FILE2, i)
  838.         = D_RELLEN (result, FILEC, current0line++);
  839.     }
  840.     }
  841.  
  842.   /* Set correspond */
  843.   if (!using[0])
  844.     D3_TYPE (result) = DIFF_3RD;
  845.   else if (!using[1])
  846.     D3_TYPE (result) = DIFF_2ND;
  847.   else
  848.     {
  849.       int nl1
  850.     = D_HIGHLINE (result, FILE1) - D_LOWLINE (result, FILE1) + 1;
  851.       int nl2
  852.     = D_HIGHLINE (result, FILE2) - D_LOWLINE (result, FILE2) + 1;
  853.  
  854.       if (nl1 != nl2
  855.       || !compare_line_list (D_LINEARRAY (result, FILE1),
  856.                  D_LENARRAY (result, FILE1),
  857.                  D_LINEARRAY (result, FILE2),
  858.                  D_LENARRAY (result, FILE2),
  859.                  nl1))
  860.     D3_TYPE (result) = DIFF_ALL;
  861.       else
  862.     D3_TYPE (result) = DIFF_1ST;
  863.     }
  864.   
  865.   return result;
  866. }
  867.  
  868. /*
  869.  * This routine copies pointers from a list of strings to a different list
  870.  * of strings.  If a spot in the second list is already filled, it
  871.  * makes sure that it is filled with the same string; if not it
  872.  * returns 0, the copy incomplete.
  873.  * Upon successful completion of the copy, it returns 1.
  874.  */
  875. int copy_stringlist (char **fromptrs, int *fromlengths,
  876.              char **toptrs, int *tolengths, int copynum)
  877. {
  878.   register char
  879.     **f = fromptrs,
  880.     **t = toptrs;
  881.   register int
  882.     *fl = fromlengths,
  883.     *tl = tolengths;
  884.   
  885.   while (copynum--)
  886.     {
  887.       if (*t)
  888.     { if (*fl != *tl || bcmp (*f, *t, *fl)) return 0; }
  889.       else
  890.     { *t = *f ; *tl = *fl; }
  891.  
  892.       t++; f++; tl++; fl++;
  893.     }
  894.   return 1;
  895. }
  896.  
  897. /*
  898.  * Create a diff3_block, with ranges as specified in the arguments.
  899.  * Allocate the arrays for the various pointers (and zero them) based
  900.  * on the arguments passed.  Return the block as a result.
  901.  */
  902. struct diff3_block *create_diff3_block (int low0, int high0,
  903.                     int low1, int high1,
  904.                     int low2, int high2)
  905. {
  906.   struct diff3_block *result = ALLOCATE (1, struct diff3_block);
  907.   int numlines;
  908.  
  909.   D3_TYPE (result) = ERROR;
  910.   D_NEXT (result) = 0;
  911.  
  912.   /* Assign ranges */
  913.   D_LOWLINE (result, FILE0) = low0;
  914.   D_HIGHLINE (result, FILE0) = high0;
  915.   D_LOWLINE (result, FILE1) = low1;
  916.   D_HIGHLINE (result, FILE1) = high1;
  917.   D_LOWLINE (result, FILE2) = low2;
  918.   D_HIGHLINE (result, FILE2) = high2;
  919.  
  920.   /* Allocate and zero space */
  921.   numlines = D_NUMLINES (result, FILE0);
  922.   if (numlines)
  923.     {
  924.       D_LINEARRAY (result, FILE0) = ALLOCATE (numlines, char *);
  925.       D_LENARRAY (result, FILE0) = ALLOCATE (numlines, int);
  926.       bzero (D_LINEARRAY (result, FILE0), (numlines * sizeof (char *)));
  927.       bzero (D_LENARRAY (result, FILE0), (numlines * sizeof (int)));
  928.     }
  929.   else
  930.     {
  931.       D_LINEARRAY (result, FILE0) = (char **) 0;
  932.       D_LENARRAY (result, FILE0) = (int *) 0;
  933.     }
  934.  
  935.   numlines = D_NUMLINES (result, FILE1);
  936.   if (numlines)
  937.     {
  938.       D_LINEARRAY (result, FILE1) = ALLOCATE (numlines, char *);
  939.       D_LENARRAY (result, FILE1) = ALLOCATE (numlines, int);
  940.       bzero (D_LINEARRAY (result, FILE1), (numlines * sizeof (char *)));
  941.       bzero (D_LENARRAY (result, FILE1), (numlines * sizeof (int)));
  942.     }
  943.   else
  944.     {
  945.       D_LINEARRAY (result, FILE1) = (char **) 0;
  946.       D_LENARRAY (result, FILE1) = (int *) 0;
  947.     }
  948.  
  949.   numlines = D_NUMLINES (result, FILE2);
  950.   if (numlines)
  951.     {
  952.       D_LINEARRAY (result, FILE2) = ALLOCATE (numlines, char *);
  953.       D_LENARRAY (result, FILE2) = ALLOCATE (numlines, int);
  954.       bzero (D_LINEARRAY (result, FILE2), (numlines * sizeof (char *)));
  955.       bzero (D_LENARRAY (result, FILE2), (numlines * sizeof (int)));
  956.     }
  957.   else
  958.     {
  959.       D_LINEARRAY (result, FILE2) = (char **) 0;
  960.       D_LENARRAY (result, FILE2) = (int *) 0;
  961.     }
  962.  
  963.   /* Return */
  964.   return result;
  965. }
  966.  
  967. /*
  968.  * Compare two lists of lines of text.
  969.  * Return 1 if they are equivalent, 0 if not.
  970.  */
  971. int compare_line_list (char **list1, int *lengths1,
  972.                char **list2, int *lengths2, int nl)
  973. {
  974.   char
  975.     **l1 = list1,
  976.     **l2 = list2;
  977.   int
  978.     *lgths1 = lengths1,
  979.     *lgths2 = lengths2;
  980.   
  981.   while (nl--)
  982.     if (!*l1 || !*l2 || *lgths1 != *lgths2++
  983.     || bcmp (*l1++, *l2++, *lgths1++))
  984.       return 0;
  985.   return 1;
  986. }
  987.  
  988. /* 
  989.  * Routines to input and parse two way diffs.
  990.  */
  991.  
  992. #define    DIFF_CHUNK_SIZE    10000
  993.  
  994. struct diff_block *process_diff (char *filea, char *fileb)
  995. {
  996.   char *diff_contents;
  997.   char *diff_limit;
  998.   char *scan_diff;
  999.   enum diff_type dt;
  1000.   int i;
  1001.   struct diff_block *block_list, *block_list_end, *bptr;
  1002.  
  1003.   diff_limit = read_diff (filea, fileb, &diff_contents);
  1004.   scan_diff = diff_contents;
  1005.   bptr = block_list_end = block_list = (struct diff_block *) 0;
  1006.  
  1007.   while (scan_diff < diff_limit)
  1008.     {
  1009.       bptr = ALLOCATE (1, struct diff_block);
  1010.       bptr->next = 0;
  1011.       bptr->lines[0] = bptr->lines[1] = (char **) 0;
  1012.       bptr->lengths[0] = bptr->lengths[1] = (int *) 0;
  1013.       
  1014.       dt = process_diff_control (&scan_diff, bptr);
  1015.       if (dt == ERROR || *scan_diff != '\n')
  1016.     {
  1017.       fprintf (stderr, "%s: diff error: ", argv0);
  1018.       do
  1019.         {
  1020.           putc (*scan_diff, stderr);
  1021.         }
  1022.       while (*scan_diff++ != '\n');
  1023.       exit (2);
  1024.     }
  1025.       scan_diff++;
  1026.       
  1027.       /* Force appropriate ranges to be null, if necessary */
  1028.       switch (dt)
  1029.     {
  1030.     case ADD:
  1031.       bptr->ranges[0][0]++;
  1032.       break;
  1033.     case DELETE:
  1034.       bptr->ranges[1][0]++;
  1035.       break;
  1036.     case CHANGE:
  1037.       break;
  1038.     default:
  1039.       fatal ("Internal: Bad diff type in process_diff");
  1040.       break;
  1041.     }
  1042.       
  1043.       /* Allocate space for the pointers for the lines from filea, and
  1044.      parcel them out among these pointers */
  1045.       if (dt != ADD)
  1046.     {
  1047.       bptr->lines[0] = ALLOCATE ((bptr->ranges[0][END]
  1048.                       - bptr->ranges[0][START] + 1),
  1049.                      char *);
  1050.       bptr->lengths[0] = ALLOCATE ((bptr->ranges[0][END]
  1051.                     - bptr->ranges[0][START] + 1),
  1052.                        int);
  1053.       for (i = 0; i <= (bptr->ranges[0][END]
  1054.                 - bptr->ranges[0][START]); i++)
  1055.         scan_diff = scan_diff_line (scan_diff,
  1056.                     &(bptr->lines[0][i]),
  1057.                     &(bptr->lengths[0][i]),
  1058.                     diff_limit,
  1059.                     '<');
  1060.     }
  1061.       
  1062.       /* Get past the separator for changes */
  1063.       if (dt == CHANGE)
  1064.     {
  1065.       if (strncmp (scan_diff, "---\n", 4))
  1066.         fatal ("Bad diff format: Bad change separator");
  1067.       scan_diff += 4;
  1068.     }
  1069.       
  1070.       /* Allocate space for the pointers for the lines from fileb, and
  1071.      parcel them out among these pointers */
  1072.       if (dt != DELETE)
  1073.     {
  1074.       bptr->lines[1] = ALLOCATE ((bptr->ranges[1][END]
  1075.                       - bptr->ranges[1][START] + 1),
  1076.                      char *);
  1077.       bptr->lengths[1] = ALLOCATE ((bptr->ranges[1][END]
  1078.                     - bptr->ranges[1][START] + 1),
  1079.                        int);
  1080.       for (i = 0; i <= (bptr->ranges[1][END]
  1081.                 - bptr->ranges[1][START]); i++)
  1082.         scan_diff = scan_diff_line (scan_diff,
  1083.                     &(bptr->lines[1][i]),
  1084.                     &(bptr->lengths[1][i]),
  1085.                     diff_limit,
  1086.                     '>');
  1087.     }
  1088.       
  1089.       /* Place this block on the blocklist */
  1090.       if (block_list_end)
  1091.     block_list_end->next = bptr;
  1092.       else
  1093.     block_list = bptr;
  1094.       
  1095.       block_list_end = bptr;
  1096.       
  1097.     }
  1098.  
  1099.   return block_list;
  1100. }
  1101.  
  1102. /*
  1103.  * This routine will parse a normal format diff control string.  It
  1104.  * returns the type of the diff (ERROR if the format is bad).  All of
  1105.  * the other important information is filled into to the structure
  1106.  * pointed to by db, and the string pointer (whose location is passed
  1107.  * to this routine) is updated to point beyond the end of the string
  1108.  * parsed.  Note that only the ranges in the diff_block will be set by
  1109.  * this routine.
  1110.  *
  1111.  * If some specific pair of numbers has been reduced to a single
  1112.  * number, then both corresponding numbers in the diff block are set
  1113.  * to that number.  In general these numbers are interpetted as ranges
  1114.  * inclusive, unless being used by the ADD or DELETE commands.  It is
  1115.  * assumed that these will be special cased in a superior routine.  
  1116.  */
  1117.  
  1118. enum diff_type process_diff_control (char **string, struct diff_block *db)
  1119. {
  1120.   char *s = *string;
  1121.   int holdnum;
  1122.   enum diff_type type;
  1123.  
  1124. /* These macros are defined here because they can use variables
  1125.    defined in this function.  Don't try this at home kids, we're
  1126.    trained professionals!
  1127.  
  1128.    Also note that SKIPWHITE only recognizes tabs and spaces, and
  1129.    that READNUM can only read positive, integral numbers */
  1130.  
  1131. #define    SKIPWHITE(s)    { while (*s == ' ' || *s == '\t') s++; }
  1132. #define    READNUM(s, num)    \
  1133.     { if (!isdigit (*s)) return ERROR; holdnum = 0;    \
  1134.       do { holdnum = (*s++ - '0' + holdnum * 10); }    \
  1135.       while (isdigit (*s)); (num) = holdnum; }
  1136.  
  1137.   /* Read first set of digits */
  1138.   SKIPWHITE (s);
  1139.   READNUM (s, db->ranges[0][START]);
  1140.  
  1141.   /* Was that the only digit? */
  1142.   SKIPWHITE(s);
  1143.   if (*s == ',')
  1144.     {
  1145.       /* Get the next digit */
  1146.       s++;
  1147.       READNUM (s, db->ranges[0][END]);
  1148.     }
  1149.   else
  1150.     db->ranges[0][END] = db->ranges[0][START];
  1151.  
  1152.   /* Get the letter */
  1153.   SKIPWHITE (s);
  1154.   switch (*s)
  1155.     {
  1156.     case 'a':
  1157.       type = ADD;
  1158.       break;
  1159.     case 'c':
  1160.       type = CHANGE;
  1161.       break;
  1162.     case 'd':
  1163.       type = DELETE;
  1164.       break;
  1165.     default:
  1166.       return ERROR;            /* Bad format */
  1167.     }
  1168.   s++;                /* Past letter */
  1169.   
  1170.   /* Read second set of digits */
  1171.   SKIPWHITE (s);
  1172.   READNUM (s, db->ranges[1][START]);
  1173.  
  1174.   /* Was that the only digit? */
  1175.   SKIPWHITE(s);
  1176.   if (*s == ',')
  1177.     {
  1178.       /* Get the next digit */
  1179.       s++;
  1180.       READNUM (s, db->ranges[1][END]);
  1181.       SKIPWHITE (s);        /* To move to end */
  1182.     }
  1183.   else
  1184.     db->ranges[1][END] = db->ranges[1][START];
  1185.  
  1186.   *string = s;
  1187.   return type;
  1188. }
  1189.  
  1190. char *read_diff (char *filea, char *fileb, char **output_placement)
  1191. {
  1192.   char *command;
  1193.   int cmd_len = strlen(diff_program) + strlen(filea) + strlen(fileb) + 10;
  1194.   FILE *fd;
  1195.   char *diff_result;
  1196.   int current_chunk_size;
  1197.   int bytes;
  1198.   int total;
  1199.  
  1200.   command = xmalloc(cmd_len);
  1201.   sprintf(command, "%s %s-- %s %s", diff_program, (always_text ? "-a" : ""),
  1202.       filea, fileb);
  1203.   fd = popen(command, "r");
  1204.   free(command);
  1205.  
  1206.   if (fd == NULL)
  1207.     fatal ("Pipe failed");
  1208.  
  1209.   current_chunk_size = DIFF_CHUNK_SIZE;
  1210.   diff_result = (char *) xmalloc (current_chunk_size);
  1211.   total = 0;
  1212.   do {
  1213.     bytes = myread (fd, diff_result + total,
  1214.             current_chunk_size - total);
  1215.     total += bytes;
  1216.     if (total == current_chunk_size)
  1217.       diff_result = (char *) xrealloc (diff_result, (current_chunk_size *= 2));
  1218.   } while (bytes);
  1219.  
  1220.   pclose(fd);
  1221.  
  1222.   if (total != 0 && diff_result[total-1] != '\n')
  1223.     fatal ("Bad diff format; Incomplete last line");
  1224.  
  1225.   *output_placement = diff_result;
  1226.  
  1227.   return diff_result + total;
  1228. }
  1229.  
  1230.  
  1231. /*
  1232.  * Scan a regular diff line (consisting of > or <, followed by a
  1233.  * space, followed by text (including nulls) up to a newline.
  1234.  *
  1235.  * This next routine began life as a macro and many parameters in it
  1236.  * are used as call-by-reference values.
  1237.  */
  1238. char *scan_diff_line (char *scan_ptr, char **set_start, int *set_length,
  1239.               char *limit, char firstchar)
  1240. {
  1241.   char *line_ptr;
  1242.  
  1243.   if (!(scan_ptr[0] == (firstchar)
  1244.     && scan_ptr[1] == ' '))
  1245.     fatal ("Bad diff format; Incorrect leading line chars");
  1246.  
  1247.   *set_start = line_ptr = scan_ptr + 2;
  1248.   while (*line_ptr++ != '\n')
  1249.     ;
  1250.  
  1251.   /* Include newline if the original line ended in a newline,
  1252.      or if an edit script is being generated.
  1253.      Copy any missing newline message to stderr if an edit script is being
  1254.      generated, because edit scripts cannot handle missing newlines.
  1255.      Return the beginning of the next line.  */
  1256.   *set_length = line_ptr - *set_start;
  1257.   if (line_ptr < limit && *line_ptr == '\\')
  1258.     {
  1259.       if (edscript)
  1260.     fprintf (stderr, "%s:", argv0);
  1261.       else
  1262.     --*set_length;
  1263.       line_ptr++;
  1264.       do
  1265.     {
  1266.       if (edscript)
  1267.         putc (*line_ptr, stderr);
  1268.     }
  1269.       while (*line_ptr++ != '\n');
  1270.     }
  1271.  
  1272.   return line_ptr;
  1273. }
  1274.  
  1275. /*
  1276.  * This routine outputs a three way diff passed as a list of
  1277.  * diff3_block's.
  1278.  * The argument MAPPING is indexed by external file number (in the
  1279.  * argument list) and contains the internal file number (from the
  1280.  * diff passed).  This is important because the user expects his
  1281.  * outputs in terms of the argument list number, and the diff passed
  1282.  * may have been done slightly differently (if the first argument in
  1283.  * the argument list was the standard input, for example).
  1284.  * REV_MAPPING is the inverse of MAPPING.
  1285.  */
  1286. void output_diff3 (FILE *outputfile, struct diff3_block *diff,
  1287.            int *mapping, int *rev_mapping)
  1288. {
  1289.   int i;
  1290.   int oddoneout;
  1291.   char *cp;
  1292.   struct diff3_block *ptr;
  1293.   int line;
  1294.   int length;
  1295.   int dontprint;
  1296.   static int skew_increment[3] = { 2, 3, 1 }; /* 0==>2==>1==>3 */
  1297.  
  1298.   for (ptr = diff; ptr; ptr = D_NEXT (ptr))
  1299.     {
  1300.       char x[2];
  1301.  
  1302.       switch (ptr->correspond)
  1303.     {
  1304.     case DIFF_ALL:
  1305.       x[0] = '\0';
  1306.       dontprint = 3;    /* Print them all */
  1307.       oddoneout = 3;    /* Nobody's odder than anyone else */
  1308.       break;
  1309.     case DIFF_1ST:
  1310.     case DIFF_2ND:
  1311.     case DIFF_3RD:
  1312.       oddoneout = rev_mapping[(int) ptr->correspond - (int) DIFF_1ST];
  1313.         
  1314.       x[0] = oddoneout + '1';
  1315.       x[1] = '\0';
  1316.       dontprint = oddoneout==0;
  1317.       break;
  1318.     default:
  1319.       fatal ("Internal: Bad diff type passed to output");
  1320.     }
  1321.       fprintf (outputfile, "====%s\n", x);
  1322.  
  1323.       /* Go 0, 2, 1 if the first and third outputs are equivalent. */
  1324.       for (i = 0; i < 3;
  1325.        i = (oddoneout == 1 ? skew_increment[i] : i + 1))
  1326.     {
  1327.       int realfile = mapping[i];
  1328.       int
  1329.         lowt = D_LOWLINE (ptr, realfile),
  1330.         hight = D_HIGHLINE (ptr, realfile);
  1331.       
  1332.       fprintf (outputfile, "%d:", i + 1);
  1333.       switch (lowt - hight)
  1334.         {
  1335.         case 1:
  1336.           fprintf (outputfile, "%da\n", lowt - 1);
  1337.           break;
  1338.         case 0:
  1339.           fprintf (outputfile, "%dc\n", lowt);
  1340.           break;
  1341.         default:
  1342.           fprintf (outputfile, "%d,%dc\n", lowt, hight);
  1343.           break;
  1344.         }
  1345.  
  1346.       if (i == dontprint) continue;
  1347.  
  1348.       for (line = 0; line < hight - lowt + 1; line++)
  1349.         {
  1350.           fprintf (outputfile, "  ");
  1351.           cp = D_RELNUM (ptr, realfile, line);
  1352.           length = D_RELLEN (ptr, realfile, line);
  1353.           fwrite (cp, sizeof (char), length, outputfile);
  1354.         }
  1355.       if (line != 0 && cp[length - 1] != '\n')
  1356.         fprintf (outputfile, "\n\\ No newline at end of file\n");
  1357.     }
  1358.     }
  1359. }
  1360.  
  1361. /*
  1362.  * This routine outputs a diff3 set of blocks as an ed script.  This
  1363.  * script applies the changes between file's 2 & 3 to file 1.  It
  1364.  * takes the precise format of the ed script to be output from global
  1365.  * variables set during options processing.  Note that it does
  1366.  * destructive things to the set of diff3 blocks it is passed; it
  1367.  * reverses their order (this gets around the problems involved with
  1368.  * changing line numbers in an ed script).
  1369.  *
  1370.  * Note that this routine has the same problem of mapping as the last
  1371.  * one did; the variable MAPPING maps from file number according to
  1372.  * the argument list to file number according to the diff passed.  All
  1373.  * files listed below are in terms of the argument list.
  1374.  * REV_MAPPING is the inverse of MAPPING.
  1375.  *
  1376.  * The arguments FILE0, FILE1 and FILE2 are the strings to print
  1377.  * as the names of the three files.  These may be the actual names,
  1378.  * or may be the arguments specified with -L.
  1379.  *
  1380.  * Returns 1 if overlaps were found.
  1381.  */
  1382.  
  1383. int output_diff3_edscript (FILE *outputfile, struct diff3_block *diff,
  1384.                int *mapping, int *rev_mapping,
  1385.                char *file0, char *file1, char *file2)
  1386. {
  1387.   int i;
  1388.   int leading_dot;
  1389.   int overlaps_found = 0;
  1390.   struct diff3_block *newblock, *thisblock;
  1391.  
  1392.   leading_dot = 0;
  1393.  
  1394.   newblock = reverse_diff3_blocklist (diff);
  1395.  
  1396.   for (thisblock = newblock; thisblock; thisblock = thisblock->next)
  1397.     {
  1398.       /* Must do mapping correctly.  */
  1399.       enum diff_type type
  1400.     = ((thisblock->correspond == DIFF_ALL) ?
  1401.        DIFF_ALL :
  1402.        ((enum diff_type)
  1403.         (((int) DIFF_1ST)
  1404.          + rev_mapping[(int) thisblock->correspond - (int) DIFF_1ST])));
  1405.  
  1406.       /* If we aren't supposed to do this output block, skip it */
  1407.       if (type == DIFF_2ND || type == DIFF_1ST
  1408.       || (type == DIFF_3RD && dont_write_simple)
  1409.       || (type == DIFF_ALL && dont_write_overlap))
  1410.     continue;
  1411.  
  1412.       if (flagging && type == DIFF_ALL)
  1413.     /* Do special flagging */
  1414.     {
  1415.  
  1416.       /* Put in lines from FILE2 with bracket */
  1417.       fprintf (outputfile, "%da\n",
  1418.            D_HIGHLINE (thisblock, mapping[FILE0]));
  1419.       fprintf (outputfile, "=======\n");
  1420.       for (i = 0;
  1421.            i < D_NUMLINES (thisblock, mapping[FILE2]);
  1422.            i++)
  1423.         {
  1424.           if (D_RELNUM (thisblock, mapping[FILE2], i)[0] == '.')
  1425.         { leading_dot = 1; fprintf(outputfile, "."); }
  1426.           fwrite (D_RELNUM (thisblock, mapping[FILE2], i), sizeof (char),
  1427.               D_RELLEN (thisblock, mapping[FILE2], i), outputfile);
  1428.         }
  1429.       fprintf (outputfile, ">>>>>>> %s\n.\n", file2);
  1430.       overlaps_found = 1;
  1431.  
  1432.       /* Add in code to take care of leading dots, if necessary. */
  1433.       if (leading_dot)
  1434.         {
  1435.           fprintf (outputfile, "%d,%ds/^\\.\\./\\./\n",
  1436.                D_HIGHLINE (thisblock, mapping[FILE0]) + 1,
  1437.                (D_HIGHLINE (thisblock, mapping[FILE0])
  1438.             + D_NUMLINES (thisblock, mapping[FILE2])));
  1439.           leading_dot = 0;
  1440.         }
  1441.  
  1442.       /* Put in code to do initial bracket of lines from FILE0  */
  1443.       fprintf (outputfile, "%da\n<<<<<<< %s\n.\n",
  1444.            D_LOWLINE (thisblock, mapping[FILE0]) - 1,
  1445.            file0);
  1446.     }
  1447.       else if (D_NUMLINES (thisblock, mapping[FILE2]) == 0)
  1448.     /* Write out a delete */
  1449.     {
  1450.       if (D_NUMLINES (thisblock, mapping[FILE0]) == 1)
  1451.         fprintf (outputfile, "%dd\n",
  1452.              D_LOWLINE (thisblock, mapping[FILE0]));
  1453.       else
  1454.         fprintf (outputfile, "%d,%dd\n",
  1455.              D_LOWLINE (thisblock, mapping[FILE0]),
  1456.              D_HIGHLINE (thisblock, mapping[FILE0]));
  1457.     }
  1458.       else
  1459.     /* Write out an add or change */
  1460.     {
  1461.       switch (D_NUMLINES (thisblock, mapping[FILE0]))
  1462.         {
  1463.         case 0:
  1464.           fprintf (outputfile, "%da\n",
  1465.                D_HIGHLINE (thisblock, mapping[FILE0]));
  1466.           break;
  1467.         case 1:
  1468.           fprintf (outputfile, "%dc\n",
  1469.                D_HIGHLINE (thisblock, mapping[FILE0]));
  1470.           break;
  1471.         default:
  1472.           fprintf (outputfile, "%d,%dc\n",
  1473.                D_LOWLINE (thisblock, mapping[FILE0]),
  1474.                D_HIGHLINE (thisblock, mapping[FILE0]));
  1475.           break;
  1476.         }
  1477.       for (i = 0;
  1478.            i < D_NUMLINES (thisblock, mapping[FILE2]);
  1479.            i++)
  1480.         {
  1481.           if (D_RELNUM (thisblock, mapping[FILE2], i)[0] == '.')
  1482.         { leading_dot = 1; fprintf (outputfile, "."); }
  1483.           fwrite (D_RELNUM (thisblock, mapping[FILE2], i), sizeof (char),
  1484.               D_RELLEN (thisblock, mapping[FILE2], i), outputfile);
  1485.         }
  1486.       fprintf (outputfile, ".\n");
  1487.       
  1488.       /* Add in code to take care of leading dots, if necessary. */
  1489.       if (leading_dot)
  1490.         {
  1491.           fprintf (outputfile, "%d,%ds/^\\.\\./\\./\n",
  1492.                D_HIGHLINE (thisblock, mapping[FILE0]) + 1,
  1493.                (D_HIGHLINE (thisblock, mapping[FILE0])
  1494.             + D_NUMLINES (thisblock, mapping[FILE2])));
  1495.           leading_dot = 0;
  1496.         }
  1497.     }
  1498.     }
  1499.   if (finalwrite) fprintf (outputfile, "w\nq\n");
  1500.   return overlaps_found;
  1501. }
  1502.  
  1503. /*
  1504.  * Read from COMMONFILE and output to OUTPUTFILE a set of diff3_ blocks DIFF
  1505.  * as a merged file.  This acts like 'ed file0 <[output_diff3_edscript]',
  1506.  * except that it works even for binary data or incomplete lines.
  1507.  *
  1508.  * As before, MAPPING maps from arg list file number to diff file number,
  1509.  * REV_MAPPING is its inverse,
  1510.  * and FILE0, FILE1, and FILE2 are the names of the files.
  1511.  *
  1512.  * Returns 1 if overlaps were found.
  1513.  */
  1514.  
  1515. int output_diff3_merge (FILE *commonfile, FILE *outputfile,
  1516.             struct diff3_block *diff,
  1517.             int *mapping, int *rev_mapping,
  1518.             char *file0, char *file1, char *file2)
  1519. {
  1520.   int c, i;
  1521.   int overlaps_found = 0;
  1522.   struct diff3_block *b;
  1523.   int linesread = 0;
  1524.  
  1525.   for (b = diff; b; b = b->next)
  1526.     {
  1527.       /* Must do mapping correctly */
  1528.       enum diff_type type
  1529.     = ((b->correspond == DIFF_ALL) ?
  1530.        DIFF_ALL :
  1531.        ((enum diff_type)
  1532.         (((int) DIFF_1ST)
  1533.          + rev_mapping[(int) b->correspond - (int) DIFF_1ST])));
  1534.  
  1535.       /* If we aren't supposed to do this output block, skip it.  */
  1536.       if (type == DIFF_2ND || type == DIFF_1ST
  1537.       || (type == DIFF_3RD && dont_write_simple)
  1538.       || (type == DIFF_ALL && dont_write_overlap))
  1539.     continue;
  1540.  
  1541.       /* Copy I lines from common file.  */
  1542.       i = D_LOWLINE (b, FILE0) - linesread - 1;
  1543.       linesread += i;
  1544.       while (0 <= --i)
  1545.     {
  1546.       while ((c = getc(commonfile)) != '\n')
  1547.         {
  1548.           if (c == EOF)
  1549.         fatal ("Input file shrank");
  1550.           putc (c, outputfile);
  1551.         }
  1552.       putc (c, outputfile);
  1553.     }
  1554.  
  1555.       if (flagging && type == DIFF_ALL)
  1556.     /* Do special flagging.  */
  1557.     {
  1558.       /* Put in lines from FILE0 with bracket.  */
  1559.       fprintf (outputfile, "<<<<<<< %s\n", file0);
  1560.       for (i = 0;
  1561.            i < D_NUMLINES (b, mapping[FILE0]);
  1562.            i++)
  1563.         fwrite (D_RELNUM (b, mapping[FILE0], i), sizeof (char),
  1564.             D_RELLEN (b, mapping[FILE0], i), outputfile);
  1565.       fprintf (outputfile, "=======\n");
  1566.       overlaps_found = 1;
  1567.     }
  1568.  
  1569.       /* Put in lines from FILE2.  */
  1570.       for (i = 0;
  1571.        i < D_NUMLINES (b, mapping[FILE2]);
  1572.        i++)
  1573.     fwrite (D_RELNUM (b, mapping[FILE2], i), sizeof (char),
  1574.         D_RELLEN (b, mapping[FILE2], i), outputfile);
  1575.  
  1576.       if (flagging && type == DIFF_ALL)
  1577.     fprintf (outputfile, ">>>>>>> %s\n", file2);
  1578.  
  1579.       /* Skip I lines in common file.  */
  1580.       i = D_NUMLINES (b, FILE0);
  1581.       linesread += i;
  1582.       while (0 <= --i)
  1583.     while ((c = getc(commonfile)) != '\n')
  1584.       if (c == EOF)
  1585.         {
  1586.           if (i || b->next)
  1587.         fatal ("Input file shrank");
  1588.           return overlaps_found;
  1589.         }
  1590.     }
  1591.   /* Copy rest of common file.  */
  1592.   while ((c = getc (commonfile)) != EOF)
  1593.     putc (c, outputfile);
  1594.   return overlaps_found;
  1595. }
  1596.  
  1597. /*
  1598.  * Reverse the order of the list of diff3 blocks.
  1599.  */
  1600. struct diff3_block *reverse_diff3_blocklist (struct diff3_block *diff)
  1601. {
  1602.   register struct diff3_block *tmp, *next, *prev;
  1603.  
  1604.   for (tmp = diff, prev = (struct diff3_block *) 0;
  1605.        tmp; tmp = next)
  1606.     {
  1607.       next = tmp->next;
  1608.       tmp->next = prev;
  1609.       prev = tmp;
  1610.     }
  1611.   
  1612.   return prev;
  1613. }
  1614.  
  1615. int myread (FILE *fd, char *ptr, int size)
  1616. {
  1617.   int result = fread (ptr, 1, size, fd);
  1618.   if (ferror(fd))
  1619.     {
  1620.       fprintf (stderr, "%s: Read failed", argv0);
  1621.       exit(2);
  1622.     }
  1623.  
  1624.   return result;
  1625. }
  1626.  
  1627. void *xmalloc (int size)
  1628. {
  1629.   void *result = malloc (size ? size : 1);
  1630.   if (!result)
  1631.     fatal ("Malloc failed");
  1632.   return result;
  1633. }
  1634.  
  1635. void *xrealloc (void *ptr, int size)
  1636. {
  1637.   void *result = realloc (ptr, size ? size : 1);
  1638.   if (!result)
  1639.     fatal ("Malloc failed");
  1640.   return result;
  1641. }
  1642.  
  1643. void fatal (char *string)
  1644. {
  1645.   fprintf (stderr, "%s: %s\n", argv0, string);
  1646.   exit (2);
  1647. }
  1648.